package com.tigercel.xiangchengyun.ui.activities

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.tencent.qq.QQ
import cn.sharesdk.wechat.friends.Wechat
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.toast
import java.util.*


class LoginActivity : AppCompatActivity(), PlatformActionListener {
    private var timeCount: TimeCount? = null
    private lateinit var authCode: String
    private lateinit var token: String
    private lateinit var user_id: String
    private lateinit var username: String
    private var perform: PreferencesUtil? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        img_back.setOnClickListener(View.OnClickListener { this.finish() })
        timeCount = TimeCount(60000, 1000)
        if (et_phoneNum.text.isEmpty()) {
            btn_getCode.isClickable = false
        }
        et_phoneNum.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                btn_getCode.isClickable = true
                btn_getCode.background = ContextCompat.getDrawable(this@LoginActivity, R.drawable.radious_shape_bg_white)
                btn_getCode.setOnClickListener(View.OnClickListener {
                    if (et_phoneNum.text.length != 11 || !et_phoneNum.text.startsWith("1")) {
                        toast("请输入正确的手机号")
                    } else {
                        et_code.isFocusable = true
                        et_code.requestFocus()
                        timeCount!!.start()
                        getCode()
                    }

                })
            }
        })
        btn_login.setOnClickListener(View.OnClickListener {
            if (et_phoneNum.text.isEmpty() or et_code.text.isEmpty()) {
                toast("请输入手机号或者验证码")
            } else {
                login()
            }

        })
        img_wechatLogin.setOnClickListener(View.OnClickListener { loginByWechat() })
        img_qqLogin.setOnClickListener(View.OnClickListener { loginByQQ() })
        perform = PreferencesUtil(this)

    }

    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            btn_getCode.background = ContextCompat.getDrawable(this@LoginActivity, R.drawable.radious_shape_bg_gray)
            btn_getCode.isClickable = false
            this@LoginActivity.btn_getCode.text = "(" + millisUntilFinished / 1000 + ") 秒后可重新获取"
        }

        override fun onFinish() {
            btn_getCode.text = "重新获取验证码"
            btn_getCode.isClickable = true
            btn_getCode.background = ContextCompat.getDrawable(this@LoginActivity, R.drawable.radious_shape_bg_white)

        }
    }

    private fun getCode() {
        OkGo.get<String>(Global.baseUrl + Global.getVerificationCode)
                .tag(this)
                .params("mobile", et_phoneNum.text.trim().toString())
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        var result = response!!.body()
                        var status = JsonUtil.get_key_string("status", result)
                        var msg = JsonUtil.get_key_string("msg", result)
                        var code = JsonUtil.get_key_string("code", result)
                        var data = JsonUtil.getList("data", result)
                        if (status == "0") {
                            authCode = JsonUtil.get_key_string("authcode", data[0])
                        } else {
                            toast(getString(R.string.getAuthCodeFaile) + code)
                        }
                    }

                })

    }

    private fun login() {
        OkGo.post<String>(Global.baseUrl + Global.loginWithAuthcode)
                .tag(this)
                .params("username", et_phoneNum.text.trim().toString())
                .params("authcode", et_code.text.trim().toString())
                .params("devicetype", "2")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        var result = response!!.body()
                        var status = JsonUtil.get_key_string("status", result)
                        var msg = JsonUtil.get_key_string("msg", result)
                        var code = JsonUtil.get_key_string("code", result)
                        var data = JsonUtil.getList("data", result)
                        if (status == "0" && msg == "success") {
                            username = JsonUtil.get_key_string("username", data[0])
                            token = JsonUtil.get_key_string("token", data[0])
                            user_id = JsonUtil.get_key_string("user_id", data[0])
//                            Global.commonUserId = user_id
//                            Global.commonUserName = username
                            perform!!.save(username, "", token, true, user_id, et_phoneNum.text.trim().toString())
                            this@LoginActivity.finish()
                        } else {
                            toast(getString(R.string.loginFaile))
                        }
                    }

                })
    }

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    Toast.makeText(this@LoginActivity, "授权登陆成功", Toast.LENGTH_SHORT).show()
                    val platform = msg.obj as Platform
                    val userId = platform.getDb().getUserId()//获取用户账号
                    val userName = platform.getDb().getUserName()//获取用户名字
                    val userIcon = platform.getDb().getUserIcon()//获取用户头像
                    val userGender = platform.getDb().getUserGender() //获取用户性别，m = 男, f = 女，如果微信没有设置性别,默认返回null
                    Toast.makeText(this@LoginActivity, "用户名：$userName  性别：$userGender", Toast.LENGTH_SHORT).show()
                }
                2 -> Toast.makeText(this@LoginActivity, "授权登陆取消", Toast.LENGTH_SHORT).show()
                3 -> Toast.makeText(this@LoginActivity, "授权登陆失败", Toast.LENGTH_SHORT).show()
            }//下面就可以利用获取的用户信息登录自己的服务器或者做自己想做的事啦!
            //。。。
        }
    }

    /**
     * 授权
     *
     * @param platform
     */
    private fun authorize(platform: Platform?) {
        if (platform == null) {
            return
        }
        if (platform.isAuthValid) {  //如果授权就删除授权资料
            platform.removeAccount(true)
        }

        platform.showUser(null) //授权并获取用户信息
    }

    override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
        val message = Message.obtain()
        message.what = 1
        message.obj = p0
        mHandler.sendMessage(message)
    }

    override fun onCancel(p0: Platform?, p1: Int) {
        val message = Message.obtain()
        message.what = 2
        message.obj = p0
        mHandler.sendMessage(message)
    }

    override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
        val message = Message.obtain()
        message.what = 3
        message.obj = p0
        mHandler.sendMessage(message)
    }

    private fun loginByQQ() {
        val qq = ShareSDK.getPlatform(QQ.NAME)
        qq.platformActionListener = this
        qq.SSOSetting(false)
        if (!qq.isClientValid) {
            Toast.makeText(this, "QQ未安装,请先安装QQ", Toast.LENGTH_SHORT).show()
        }
        authorize(qq)
    }

    private fun loginByWechat() {
        val wechat = ShareSDK.getPlatform(Wechat.NAME)
        wechat.platformActionListener = this
        wechat.SSOSetting(false)
        if (!wechat.isClientValid) {
            Toast.makeText(this, "微信未安装,请先安装微信", Toast.LENGTH_SHORT).show()
        }
        authorize(wechat)
    }
}
